package com.liliya.servlet.ad;

import com.liliya.dao.impl.AdDaoImpl;
import com.liliya.pojo.Ad;
import com.liliya.service.impl.AdServiceImpl;
import com.liliya.utils.UploadFileUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2021/1/8 10:39
 */
@WebServlet(urlPatterns = "/ad/fileupload")
public class AdAddServlet extends HttpServlet {
    AdServiceImpl adService = new AdServiceImpl();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = "",adName = "",adComment = "",userFileName = "";
        //如果这个是普通的表单,那就直接结束方法
        if (!ServletFileUpload.isMultipartContent(req)) {
            return;
        }
        //上传文件的目录最好在web-inf下面，安全，用户无法直接访问
        String uploadPath = this.getServletContext().getRealPath("/upload/img");

        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        //缓存  -- 临时文件：如果文件超过了预期的大小，那就把这个文件放到临时文件中华，过几天再删除
        String temPath = this.getServletContext().getRealPath("/WEB-INF/tem");
        System.out.println(uploadPath);
        File temFile = new File(temPath);
        if (!temFile.exists()) {
            temFile.mkdir();
        }

        //1. 创建 DiskFileItemFactory 用于限制文件大小之类的参数，如果不写的话，那就是默认值了
        DiskFileItemFactory factory = UploadFileUtil.getDiskFileItemFactory(temFile);

        //2. 获取ServletFileUpload
        ServletFileUpload upload = UploadFileUtil.getServletFileUpload(factory);

        //3. 把前端的请求封装成一个FileItem对象 （每一个表单对象）
        // System.out.println("表单字段的name："+fileItem.getFieldName());
//        System.out.println("表单字段的value"+fileItem.getString("utf-8"));
        try {
            List<FileItem> fileItems = upload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {//如果这个是普通的表单就正常的流程
                    String inputName = fileItem.getFieldName();
                    if (inputName.equals("adname")) {
                        adName = fileItem.getFieldName();
                    } else if (inputName.equals("adcomment")) {
                        adComment = fileItem.getString("utf-8");
                    }

                } else {  //处理文件
                    String uploadFileName = fileItem.getName();
                    if (uploadFileName.trim().equals("") || uploadFileName == null) { //文件名不合法
                        continue;
                    }

                    //获取上传的文件名
                    fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                    userFileName = fileName;
                    String dateTime = new SimpleDateFormat("YYMMddHHmmssSSSS").format(System.currentTimeMillis());
                    fileName = dateTime + "_" + fileName;

                    fileItem.write(new File(uploadPath + "/" + fileName));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Ad ad = new Ad();
        ad.setAdname(adName);
        ad.setAdcomment(adComment);
        ad.setAdalt(userFileName);
        ad.setAdlink("/upload/img/" + fileName);
        adService.addAd(ad);
        //这个是展示图片的
//        resp.sendRedirect("../upload/img/" + fileName);
        resp.sendRedirect(req.getContextPath()+"/ad/manage");
    }
}
